package com.teama4.shop.controller;

import com.teama4.shop.domain.Commodity;
import com.teama4.shop.service.CommodityService;
import com.teama4.shop.utils.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Controller
@RequestMapping("/Commodity")
public class CommodityController {
    @Autowired
    private CommodityService commodityService;

    @DeleteMapping("/deleteCommodity")
    @ResponseBody
    public Boolean deleteCommodity(@RequestParam("id") int id) {
        int deleted = commodityService.deleteByPrimaryKey(id);
        return deleted > 0;
    }

    @GetMapping("/goToAddPage")
    public String goToAddPage(Model model, int store_Id){
        Commodity commodity = new Commodity();
        commodity.setStoreId(store_Id);
        model.addAttribute("commodity", commodity);
        model.addAttribute("title", "增加商品");
        return "/merchant/commodity-add";
    }

    @GetMapping("/findCommodity")
    public String findCommodity(@RequestParam("id") int id, Model model) {
        Commodity commodity = commodityService.selectByPrimaryKey(id);
        model.addAttribute("commodity", commodity);
        model.addAttribute("title", "修改商品");
        return "/merchant/commodity-add";
    }


    @PostMapping("/addCommodity")
    public String addCommodity(Model model, Commodity commodity, MultipartFile file) throws IOException {
        String filePath = "/myFile/img/commodityPic";
        String filename = file.getOriginalFilename();
        String sname = filename.substring(filename.lastIndexOf("."));
        String name = UUID.randomUUID() + sname;
        commodity.setComPicture(name);
        FileUtil.dictionary_add(file, filePath, name);
        commodityService.saveCommodity(commodity);
        model.addAttribute("id", commodity.getStoreId());
        return "redirect:/index/commodityList";
    }
}
